﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Text;
using System.Web;
using CoreLibrary;
using HtmlAgilityPack;
using ScrapySharp.Extensions;
using Yamato.Common;

namespace UserLibrary
{
    class Program
    {
        static void Main(string[] args)
        {
            
            Console.ReadKey();
        }

        public static void ExecuteSql()
        {
            string dir = @"E:\Project\EhnPortal\02 Development Library\database\Script\团检\";
            StringBuilder sql = new StringBuilder();
            try
            {
                int fileCount = 0;
                ListFiles(new DirectoryInfo(dir), ref fileCount, sql);
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message);
            }
        }

        public static void ListFiles(FileSystemInfo info, ref int fileCount, StringBuilder sql)
        {
            if (!info.Exists) return;
            DirectoryInfo dir = info as DirectoryInfo;      //不是目录      
            if (dir == null) return;
            FileSystemInfo[] files = dir.GetFileSystemInfos();
            string strLine;

            for (int i = 0; i < files.Length; i++)
            {

                FileInfo file = files[i] as FileInfo;        //是文件         
                if (file != null)
                {
                    fileCount++;
                    FileStream fs = new FileStream(file.FullName, FileMode.Open);

                    StreamReader m_streamReader = new StreamReader(fs);

                    m_streamReader.BaseStream.Seek(0, SeekOrigin.Begin);

                    while (!string.IsNullOrEmpty(strLine = m_streamReader.ReadLine()))
                    {

                    }
                    Console.WriteLine(file.FullName + "\t " + fileCount);
                }
                else
                { //对于子目录，进行递归调用 
                    ListFiles(files[i], ref fileCount, sql);
                }
            }
        }

        /// <summary>
        /// 更新会员密码
        /// </summary>
        private static void UpdateMemeberPassword()
        {
            DataTable dt = GetMemebers();
            string decPwd;
            string encPwd;
            int index = 1;
            foreach (DataRow dataRow in dt.Rows)
            {
                if (string.IsNullOrEmpty(EncryptUtil.Decrypt(dataRow["m_Password"].ToString())))
                {
                    decPwd = dataRow["pwd"].ToString();
                    encPwd = EncryptUtil.Encrypt(dataRow["pwd"].ToString());
                    UpdatePwd(Convert.ToInt32(dataRow["memberid"]), encPwd);
                    Console.WriteLine(index + ":" + decPwd + "===>" + encPwd);
                    index++;
                }
            }
            Console.ReadKey();
        }

        /// <summary>
        /// 更新密码
        /// </summary>
        /// <returns></returns>
        private static void UpdatePwd(int memberId, string pwd)
        {
            string sql = "UPDATE dbo.wt_CorporateMember SET m_Password='" + pwd + "' WHERE memberid=" + memberId;
            SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionString, CommandType.Text, sql);
        }

        /// <summary>
        /// 获取会员列表
        /// </summary>
        /// <returns></returns>
        private static DataTable GetMemebers()
        {
            string sql = @"SELECT  t.memberid ,
                                    m_Password ,
                                    SUBSTRING(m_StaffCode,LEN(m_StaffCode)-5,6) pwd
                            FROM    wt_CorporateMember t
                            WHERE   t.m_CustomCode = 'Nicole040-2014'
                                    AND Prop <> 2
                                    AND LEN(m_Password) = 16";
            DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.ConnectionString, CommandType.Text, sql);
            if (ds != null && ds.Tables.Count > 0)
            {
                return ds.Tables[0];
            }
            else
            {
                return null;
            }
        }

        private static void GetHtmlDoc(string html)
        {

            var htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(html);
            var docNode = htmlDocument.DocumentNode;

            var liNodes = docNode.CssSelect("ul li a");
            string href = string.Empty;
            string value;
            foreach (HtmlNode node in liNodes)
            {
                href = node.GetAttributeValue("href", href);
                value = node.InnerText;
                Console.WriteLine(href + ":" + value);
            }
        }

        /// <summary>
        /// 获取网页Html内容
        /// </summary>
        /// <param name="url">请求的URL</param>
        /// <param name="postParams">请求的参数集合</param>
        /// <param name="requestModel">请求主机头信息</param>
        /// <returns></returns>
        private static string GetPageHtml(string url, Dictionary<string, string> postParams, HttpRequestModel requestModel)
        {
            //随机数
            Random r = new Random();
            decimal rn = (decimal)r.Next(1, 9) / (decimal)r.Next(10, 100);
            url = url + "?randomNum" + rn;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            //Cookie信息
            request.CookieContainer = new CookieContainer();
            CookieContainer cookie = request.CookieContainer;

            //发送的http头 
            request.Referer = requestModel.Referer;
            request.Accept = requestModel.Accept;
            request.Headers["Accept-Language"] = requestModel.AcceptLanguage;
            request.UserAgent = requestModel.UserAgent;
            request.KeepAlive = requestModel.KeepAlive;
            request.ContentType = requestModel.ContentType;
            request.Method = requestModel.Method;

            //TODO:动态获取编码格式
            Encoding encoding = Encoding.GetEncoding("GB2312");
            string postParamsString = string.Empty;
            foreach (KeyValuePair<string, string> postItem in postParams)
            {
                postParamsString += string.IsNullOrEmpty(postParamsString)
                                        ? postItem.Key + "=" + HttpUtility.UrlEncode(postItem.Value)
                                        : "&" + postItem.Key + "=" + HttpUtility.UrlEncode(postItem.Value);
            }

            byte[] postData = encoding.GetBytes(postParamsString);
            request.ContentLength = postData.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(postData, 0, postData.Length);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();

            //如果http头中接受gzip的话，这里就要判断是否为有压缩，有的话，直接解压缩即可  
            if (response.Headers["Content-Encoding"] != null && response.Headers["Content-Encoding"].ToLower().Contains("gzip"))
            {
                responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
            }

            StreamReader streamReader = new StreamReader(responseStream, encoding);
            string retString = streamReader.ReadToEnd();

            streamReader.Close();
            if (responseStream != null)
            {
                responseStream.Close();
            }

            return retString;
        }
    }

    class HttpRequestModel
    {
        public string Referer;
        public string Accept;
        public string AcceptLanguage;
        public string UserAgent;
        public bool KeepAlive;
        public string ContentType;
        public string Method;
    }
}
